<template>
  <div class="e-item">
    <span class="title" :style="`vertical-align:top;margin-top: 10px;width:${width}px !important;`">{{title}}</span>
    <div class="dis-block" >
      <div class="imgBox">
        <img v-lazy="imgSrc" alt="">
      </div>
      <input type="file" ref="imgInput" @change="changeImg" accept='image/*' style="display: none;">
      <button type='button' class="browse" @click="chooseImg">浏览</button>
    </div>
  </div>
</template>

<script>
import { apiDecorateMange } from 'js/api'
import { mapGetters } from 'vuex'

export default {
  props: {
    title: {
      type: String,
      default: '图片'
    },
    width: {
      type: Number,
      default: 105
    },
    type: {
      type: String,
      default: 'advert'
    },
    imgSrc: String
  },
  computed: {
    ...mapGetters(['token'])
  },
  methods: {
    // 与 图片上传 中的按钮绑定
    chooseImg() {
      this.$refs.imgInput.click()
    },
    // FileReader 图片预览 
    changeImg() {
      // let reader = new FileReader()
      // let that = this
      // reader.readAsDataURL(this.$refs.imgInput.files[0])
      // reader.onload = function(e) {
      //   that.imgSrc = this.result
      // }
      const type = this.type.toLowerCase()
      const file = this.$refs.imgInput.files[0]
      if (!file) return
      if (file.size > 1048576*4) {
        this.$toast('图片大小不能超过4M')
        return
      }
      if (!/\.(png|jpeg|jpg|gif)/i.test(file.name)) {
        this.$toast('请选择JPG,JPEG,PNG,GIF格式的图片')
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('accessToken', this.token)
      formData.append('type', type)
      apiDecorateMange.uploadImg(formData).then(data => {
        if (data.code != '200') return
        this.$toast('上传成功', () => {
          this.$emit('on-img', data.data.url)
        })
      })
    }
  }
}
</script>

<style lang='scss' scoped>
@import '../../../scss/_var.scss';
@import '../../../scss/_comment.scss';
.imgBox {
  width: 54px;
  height: 54px;
  display: inline-block;
  border: 1px solid $border-gray-light;
}
.e-item {
  .title {
    margin-right: 20px;
  }
}
</style>